<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>员工列表</title>
    <%
        pageContext.setAttribute("APP_PATH", request.getContextPath());
    %>
    <script type="text/javascript" src="${APP_PATH}/static/js/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="${APP_PATH}/static/js/bootstrap-3.4.1-dist/css/bootstrap.min.css">
    <script src="${APP_PATH}/static/js/bootstrap-3.4.1-dist/js/bootstrap.min.js"></script>
</head>
<body>
<%--员工修改的模态框--%>
<!-- Modal -->
<div class="modal fade" id="empupdateModalBtn" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">员工修改</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="update_emp_form">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <p class="form-control-static" id="empname_update_static"></p>
                            </span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email_add_input" class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="text" name="email" class="form-control" id="email_update_input"
                                   placeholder="email@qq.com">
                            <span class="help-block">
                            </span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender1_update_input" value="M" checked="checked">
                                男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender2_update_input" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <%--部门提交部门id即可--%>
                    <div class="form-group">
                        <label class="col-sm-2 control-label ">department</label>
                        <div class="col-sm-4">

                            <select id="dept_update_select" class="form-control" name="dId">

                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="empupdate_save_btn">更新</button>
            </div>
        </div>
    </div>
</div>
<%--员工添加的模态框--%>
<!-- Modal -->
<div class="modal fade" id="empAddModalBtn" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">员工添加</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="add_emp_form">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10">
                            <input type="text" name="empName" class="form-control" id="empname_add_input"
                                   placeholder="empName">
                            <span class="help-block">
                            </span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email_add_input" class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10">
                            <input type="text" name="email" class="form-control" id="email_add_input"
                                   placeholder="email@qq.com">
                            <span class="help-block">
                            </span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender1_add_input" value="M" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" id="gender2_add_input" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <%--部门提交部门id即可--%>
                    <div class="form-group">
                        <label class="col-sm-2 control-label ">department</label>
                        <div class="col-sm-4">

                            <select id="dept_add_select" class="form-control" name="dId">

                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="emp_save_btn">保存</button>
            </div>
        </div>
    </div>
</div>
<%--搭建显示页面--%>
<div class="container">
    <%--标题--%>
    <div class="row">
        <div class="col-md-12">
            <h1>
                SSM-CRUD
            </h1>
        </div>
    </div>
    <%--按钮--%>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button class="btn btn-primary" id="emp_add_modal_btn">新增</button>
            <button class="btn btn-danger">删除</button>
        </div>
    </div>
    <%--显示表格数据--%>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover" id="emps_table">
                <thead>
                <tr>
                    <th>#</th>
                    <th>lastname</th>
                    <th>email</th>
                    <th>gender</th>
                    <th>deptName</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
        </div>
    </div>
    <%--显示分页信息--%>
    <div class="row">

        <%--分页文字信息--%>
        <div id="page_info_area" class="col-md-6">
        </div>
        <%--分页按钮--%>
        <div id="page_nav_area" class="col-md-6">
        </div>
    </div>

</div>
<script type="text/javascript">
    //1.页面加载完成以后，直接去发送ajax请求，要到分页数据
    var totalRecord;
    $(function () {
        toPage(1);
    });

    function build_emps_table(result) {
        $("#emps_table tbody").empty();
        var emps = result.extend.pageInfo.list;
        $.each(emps, function (index, item) {
            var empIdTd = $("<td></td>").append(item.empId);
            var empNameTd = $("<td></td>").append(item.empName);
            var genderTd = $("<td></td>").append(item.gender == "M" ? "男" : "女");
            var emailTd = $("<td></td>").append(item.email);
            var departmentNameTd = $("<td></td>").append(item.department.deptName);
            var editButton = $("<button></button>").addClass("btn btn-primary btn-sm").append($("<span></span>").addClass("glyphicon glyphicon-pencil edit_Button")).append("编辑");
            //为编辑按钮添加一个自定义的属性，来表示当前员工的id
            editButton.attr("edit-id", item.empId);

            var DeleteButton = $("<button></button>").addClass("btn btn-danger btn-sm").append($("<span></span>").addClass("glyphicon glyphicon-trash Delete_Button")).append("删除");
            var addDeleteBtn = $("<td></td>").append(editButton).append(" ").append(DeleteButton);
            //apend方法执行完以后还会返回原来的元素
            $("<tr></tr>").append(empIdTd).append(empNameTd).append(genderTd).append(emailTd).append(departmentNameTd).append(addDeleteBtn).appendTo("#emps_table tbody");
        });
    };

    function toPage(pn) {
        $(function () {
            $.ajax({
                url: "${APP_PATH}/emps",
                data: "pn=" + pn,
                type: "get",
                success: function (result) {
                    // console.log(result);
                    //1.解析并显示员工数据
                    build_emps_table(result);

                    //2.解析并显示分页数据信息
                    build_page_nav(result);
                    //3.解析并显示分页条数据信息
                    build_page_navtiao(result);
                }

            });
        });
    };


    function build_page_nav(result) {
        $("#page_info_area").empty();
        var info = result.extend.pageInfo;
        totalRecord = result.extend.pageInfo.total;
        $("#page_info_area").append("当前第" + info.pageNum + "页，共有" + info.pages + "页，共计" + info.total + "条记录");
    }

    function build_page_navtiao(result) {
        $("#page_nav_area").empty();
        var ul = $("<ul></ul>").addClass("pagination");
        var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href", "#"));

        var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;"));

        if (!result.extend.pageInfo.hasPreviousPage) {
            firstPageLi.addClass("disabled");
            prePageLi.addClass("disabled");
        } else {
            firstPageLi.click(function () {
                toPage(1);
            });
            prePageLi.click(function () {
                toPage(result.extend.pageInfo.pageNum - 1);
            });
        }

        var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;"));
        var lastPageLi = $("<li></li>").append($("<a></a>").append("尾页").attr("href", "#"));

        if (!result.extend.pageInfo.hasNextPage) {
            nextPageLi.addClass("disabled");
            lastPageLi.addClass("disabled");
        } else {
            nextPageLi.click(function () {
                toPage(result.extend.pageInfo.pageNum + 1);
            });
            lastPageLi.click(function () {
                toPage(result.extend.pageInfo.total);
            });
        }

        ul.append(firstPageLi).append(prePageLi);
        $.each(result.extend.pageInfo.navigatepageNums, function (index, item) {

            var numLi = $("<li></li>").append($("<a></a>").append(item).attr("href", "#"));
            if (result.extend.pageInfo.pageNum == item) {
                numLi.addClass("active")
            }
            numLi.click(function () {
                toPage(item);
            });
            ul.append(numLi);
        });
        ul.append(nextPageLi).append(lastPageLi);
        var nav = $("<nav></nav>").attr("aria-label", "Page navigation").append(ul);
        nav.appendTo("#page_nav_area");
    };

    //表单的重置方法
    function reset_form(ele) {
        $(ele)[0].reset();
        $(ele).find("*").removeClass("has-success has-error");

        $(ele).find(".help-block").text("");

    }

    //点击弹出模态框。增加用户
    $("#emp_add_modal_btn").click(function () {
        //清楚表单数据和表单样式
        reset_form("#empAddModalBtn form");

        //发送ajax请求，查出部门信息，显示在下拉列表中
        getDepts("#empAddModalBtn select");


        $("#empAddModalBtn").modal({
            backdrop: "static"
        });
    });

    //查出所有的部门信息
    function getDepts(ele) {
        //清空之前下拉列表的值
        $(ele).empty();
        $.ajax({
            url: "${APP_PATH}/depts",
            type: "get",
            success: function (resultDept) {

                $.each(resultDept.extend.depts, function () {
                    // deptId":1,"deptName":"开发部
                    var option = $("<option></option>").append(this.deptName).attr("value", this.deptId);
                    option.appendTo(ele);
                });

            }
        });
    };

    //校验表单数据
    function validate_add_form() {
        //    1.拿到要校验的名字和邮箱

        var empName = $("#empname_add_input").val();
        var regName = /(^[a-z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/;
        if (!regName.test(empName)) {
            // alert("用户名可以是2到5位的中文,或者6到16位的英文")
            show_validate_msg("#empname_add_input", "error", "用户名可以是2到5位的中文,或者6到16位的英文");

            return false;
        }
        show_validate_msg("#empname_add_input", "success", "用户名合法");

        var empEmail = $("#email_add_input").val();
        var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if (!regEmail.test(empEmail)) {
            show_validate_msg("#email_add_input", "error", "邮箱格式不正确");
            // $("#email_add_input").parent().addClass("has-error");
            // $("#email_add_input").next("span").text("邮箱格式不正确");
            // alert("邮箱格式不正确");
            return false;
        }
        show_validate_msg("#email_add_input", "success", "邮箱格式合法");
        // $("#email_add_input").parent().addClass("has-success");
        // $("#email_add_input").next("span").text("邮箱格式合法");
        return true;

    };

    //    显示校验结果的提示信息
    function show_validate_msg(ele, status, msg) {
        $(ele).parent().removeClass("has-success").removeClass("has-error");
        $(ele).next("span").text();
        if ("success" == status) {
            $(ele).parent().addClass("has-success");
            $(ele).next("span").text(msg);
        } else if ("error" == status) {
            $(ele).parent().addClass("has-error");
            $(ele).next("span").text(msg);

        }

    }

    //    校验用户名是否可用
    $("#empname_add_input").change(function () {
        //    发送ajax请求校验用户名是否可用
        var empName = $("#empname_add_input").val();
        $.ajax({
            url: "${APP_PATH}/checkUser",
            data: "empName=" + empName,
            type: "POST",
            success: function (result) {
                if (result.code == 200) {
                    //    不可用
                    // alert(result.msg);
                    show_validate_msg("#empname_add_input", "error", result.extend.va_msg);
                    $("#emp_save_btn").attr("ajax-va", "error");
                } else if (result.code == 100) {
                    //    可用
                    // alert(result.msg);
                    show_validate_msg("#empname_add_input", "success", "用户名可用");
                    $("#emp_save_btn").attr("ajax-va", "success");
                }
            }
        });


    });


    $("#emp_save_btn").click(function () {

        if (!validate_add_form()) {
            return false;
        }
        if ($(this).attr("ajax-va") == "error") {
            return false;
        }

        $.ajax({
            url: "${APP_PATH}/emp",
            type: "POST",
            data: $("#add_emp_form").serialize(),
            success: function (result) {
                //如果返回的状态码是100是成功，200是失败
                if (result.code == 100) {
                    //员工保存成功：
                    //1.关闭模态框
                    $("#empAddModalBtn").modal("hide");
                    //2.来到最后一页,显示刚才保存的数据
                    toPage(totalRecord);
                } else {
                    console.log();

                }

                // alert($("#empAddModalBtn form").serialize());


            }
        });
    });
    //    jquery新版没有live方法，使用on来替代
    //    我们是在按钮创建之前就绑定了click，所以绑定不上
    $(document).on("click", ".edit_Button", function () {
        alert($(".edit_Button").prop("edit-id"));
        //    1.弹出模态框，查出部门信息和员工信息
        getEmp(3);
        //
        getDepts("#empupdateModalBtn select");
        $("#empupdateModalBtn").modal({
            backdrop: "static"
        });
    });

    function getEmp(empId) {
        $.ajax({
            url: "${APP_PATH}/emp/"+empId,
            type: "GET",
            success: function (result) {
                console.log(result);
            }
        });

    }

</script>
</body>
</html>
